package guis.visitant;

import exceptions.RepositoryException;
import guis.RegisterPanel;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JTable;

import utils.Date;
import classes.Classroom;
import classes.Visitant;

import communication.Facade;

public class EditVisitantWindow extends VisitantWindow
{
	private static final long	serialVersionUID	= 1032307379765488755L;
	private Visitant			visitant;

	public EditVisitantWindow( JFrame source, RegisterPanel< Visitant > registerPanel, Facade facade )
	{
		super( "Editar Visitante", "editar", source, registerPanel, facade );
		createActions();
		loadClassroom();
	}

	private void createActions()
	{
		cancelButton.addActionListener( new ActionListener()
		{

			@Override
			public void actionPerformed( ActionEvent arg0 )
			{
				setVisible( false );
			}

		} );

		actionButton.addActionListener( new ActionListener()
		{

			@Override
			public void actionPerformed( ActionEvent arg0 )
			{
				String name = nameTextField.getText();
				int day = ( Integer ) dayComboBox.getSelectedItem();
				int month = ( Integer ) monthComboBox.getSelectedItem();
				int year = ( Integer ) yearComboBox.getSelectedItem();
				Classroom classroom = ( Classroom ) classroomComboBox.getSelectedItem();
				int classroomId = 0;
				if ( classroom != null )
					classroomId = classroom.getId();

				visitant.setName( name );
				visitant.setVisitDate( new utils.Date( day, month, year ) );
				visitant.setVisitedClassId( classroomId );
				visitant.setId( visitant.getId() );

				try
				{
					facade.editVisitant( visitant );
					registerPanel.loadTable( null );
					setVisible( false );
				}
				catch ( RepositoryException e )
				{

				}
			}

		} );
	}
	
	private void loadClassroom()
	{
		JTable table = registerPanel.getTable();
		int selectedIndex = table.getSelectedRow();
		
		int id = Integer.parseInt( ( String ) table.getModel().getValueAt( selectedIndex, 0 ) );
		String name = ( String ) table.getModel().getValueAt( selectedIndex, 1 );
		Date visitDate = ( Date ) table.getModel().getValueAt( selectedIndex, 2 );
		Classroom classroom = ( Classroom ) table.getModel().getValueAt( selectedIndex, 3 );
		int visitedClassId = 0;
		if ( classroom != null ) visitedClassId = classroom.getId();
		
		this.visitant = new Visitant( name, visitDate, visitedClassId );
		visitant.setId( id );
		
		nameTextField.setText( name );
		dayComboBox.setSelectedItem( visitDate.getDay() );
		monthComboBox.setSelectedItem( visitDate.getMonth() );
		yearComboBox.setSelectedItem( visitDate.getYear() );
		classroomComboBox.setSelectedItem( classroom );
	}
}
